//
//  ProductTypeViewController.m
//  PrintPort
//
//  Created by hy002 on 2018/1/4.
//  Copyright © 2018年 HUAYU. All rights reserved.
//

#import "ProductTypeViewController.h"
#import "SecondTypeModel.h"
#import "ChildrenModel.h"
#import "ProductListViewController.h"

static NSString *cellPath = @"ProductAllTypeCell";
static NSString * CellIdentifier = @"HomecollectCell";
static NSString * CellIHerder = @"ProductHerderCell";
@interface ProductTypeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>
{
    CGFloat width;
}
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSArray *allTypeAry;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, assign)NSInteger leftType;
@property (nonatomic, strong)NSArray *childrenAry;

@end

@implementation ProductTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    width = SCREEN_WIDTH-10*displaywidth;
    if (_isAll)
    {
        width = SCREEN_WIDTH-100*displaywidth;

    }
    _leftType = 0;
    [self creatUI];
    [self loadNewHeaderData];
    
}

- (void)creatUI
{
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = _titStr;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    CGFloat X = 5*displaywidth;
    CGFloat W = SCREEN_WIDTH-10*displaywidth;
    if (_isAll)
    {
        self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 75*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT) style:UITableViewStylePlain];
        _tableview.backgroundColor = BacksColor;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.hidden = YES;
        [self.view addSubview:_tableview];
        _tableview.hidden = NO;
        X = 80*displaywidth;
        W = SCREEN_WIDTH-85*displaywidth;
    }
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(X, 10*displaywidth, W, SCREEN_HEIGHT-STA_NAV_HEIGHT-20*displaywidth) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
//    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIHerder];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    [self.view addSubview:_collectionView];
}

- (void)loadNewHeaderData
{
    if (_isAll)
    {
        NSDictionary *dic = @{@"area":_areaid,
                              @"zlevel":@"1"};
        [self requestProductionType:dic];
    }
    else
    {
        NSDictionary *dic = @{@"area":_areaid,
                              @"parentId":s_str(_parentId),
                              @"zlevel":@"2"};
        [self requestProductionType:dic];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allTypeAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_allTypeAry.count > 0)
    {
        UIColor *cellBack = [UIColor whiteColor];
        UIColor *nameColor = RGB(77, 77, 77);
        BOOL hide = YES;
        if (indexPath.row == _leftType)
        {
            cellBack = BacksColor;
            nameColor = ThemeColor;
            hide = NO;
        }
        cell.backgroundColor = cellBack;
        SecondTypeModel *typeModel = _allTypeAry[indexPath.row];
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(5*displaywidth, 0, 65*displaywidth, 50*displaywidth) Font:13.0 Text:typeModel.typeName Color:nameColor];
        nameLab.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:nameLab];
        UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(0, 49*displaywidth, 75*displaywidth, 1*displaywidth)];
        lineAview.backgroundColor = BacksColor;
        [cell.contentView addSubview:lineAview];
        UIView *closeBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5*displaywidth, 50*displaywidth)];
        closeBackView.backgroundColor = ThemeColor;
        closeBackView.hidden = hide;
        [cell.contentView addSubview:closeBackView];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _leftType = indexPath.row;
    SecondTypeModel *model = _allTypeAry[_leftType];
    _childrenAry = model.children;
    [tableView reloadData];
    [_collectionView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*displaywidth;
}




- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_isAll)
    {
        return _childrenAry.count;
    }
    return _allTypeAry.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    if (_allTypeAry.count > 0)
    {
        SecondTypeModel *model;
        CGFloat sizeW = 60*displaywidth;
        if (_isAll)
        {
            model = _childrenAry[indexPath.row];
            sizeW = 50*displaywidth;
        }
        else
        {
            model = _allTypeAry[indexPath.row];
        }
        cell.backgroundColor = [UIColor whiteColor];
        CGFloat W = width/4;
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake((W-sizeW)/2, 15*displaywidth, sizeW, sizeW) ImageName:@"face222"];
        [imgView sd_setImageWithURL:URL(model.imgUrl) placeholderImage:IMAGE(@"face222")];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:imgView];
        UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(0, 75*displaywidth, W, 35*displaywidth) Font:12.0 Text:model.typeName Color:RGB(77, 77, 77)];
        titlab.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:titlab];
    }
    
    
    return cell;
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(width/4, 110*displaywidth);
}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //cell被电击后移动的动画
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
    SecondTypeModel *model;
    if (_isAll)
    {
        model = _childrenAry[indexPath.row];
    }
    else
    {
        model = _allTypeAry[indexPath.row];
    }
    if (model.children.count == 0)
    {
        [LTools showMBProgressWithText:@"该分类暂无商品" addToView:self.view];
        return;
    }
    ProductListViewController *vc = [[ProductListViewController alloc] init];
    vc.allTypeAry = model.children;
    vc.modelID = s_str(model.ID);
    if ([_areaid isEqualToString:@"4"])
    {
        vc.isTH = YES;
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}


//-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//
//    CGSize size = {SCREEN_WIDTH, 30*displaywidth};
//    return size;
//
//}


//在表头内添加内容,需要创建一个继承collectionReusableView的类,用法类比tableViewcell
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    UICollectionReusableView *headerView = nil;
//    if (kind == UICollectionElementKindSectionHeader)
//    {
//        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIHerder forIndexPath:indexPath];
//        headerView.backgroundColor = BacksColor;
//        for (id subView in headerView.subviews) {
//            [subView removeFromSuperview];
//        }
//        SecondTypeModel *model = _allTypeAry[indexPath.section];
//        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, 30*displaywidth) Font:13.0 Text:model.typeName Color:BlaTiColor];
//        [headerView addSubview:nameLab];
//    }
//    return headerView;
//}





- (void)requestProductionType:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_productType Parmers:dic Success:^(id obj) {
        [weakSelf.collectionView.mj_header endRefreshing];
        if ([obj server_Getcodecheck])
        {
            weakSelf.allTypeAry = [SecondTypeModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.isAll)
                {
                    SecondTypeModel *model = _allTypeAry[_leftType];
                    weakSelf.childrenAry = model.children;
                    [weakSelf.tableview reloadData];
                }
                [weakSelf.collectionView reloadData];
                
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
